<?php 
//all the class/function includes are managed in the includer file
include("include/includer.php");

//get all the configuration variables (custom function in newzbook.php include)
getConfigVars();  

//Get all the URL parameters (_GET)
$action = $newzbinreportID = $reportname = $category = null;

if(isset($_GET['action'])) {
  $action = $_GET['action'];
}
if(isset($_GET['reportid'])) {
  //get the content of the URL parameter
  $newzbinreportID = $_GET['reportid'];
  //check if the content looks like a URL
  if(preg_match('/http\:\/\//',$newzbinreportID)){
    //if the content looks like a URL, let's try to parse out the reportID
    preg_match('/\/post\/([0-9]+)\//',$newzbinreportID,$matches);
    $newzbinreportID = $matches[1];
  }
}
if(isset($_GET['reportName'])){
	$reportName = $_GET['reportName'];
}
if(isset($_GET['category'])) {
	$category = $_GET['category'];
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<HEAD>
    <?php standardHead("Bookmarks"); ?>
</HEAD>

<BODY>
<?php internetSecurity(); ?>
<div style="visibility:hidden;display:none;" id="progress"><div id="progress_bg"></div><a name="loading" /><div id="progress_box"><img id="progress_image" style="padding-left:5px;padding-top:5px;" src="images/ajax-loader.gif" alt="loading...">Your request is being processed...</div></div>
<div class="headercontent">
  <?php headerContent(); ?>
</div>
<div class="maincontent">
  Please send any questions or comments to <?php echo "<a href='mailto:".$cfg->get("Owner","email")."'>".$cfg->get("Owner","firstname")." ".$cfg->get("Owner","lastname")."</a>";?>.
  <br />
<?php 
if(!is_dir($config_NZBDropPath)) {
  echo "<div class='warningmessage'>The NZB Drop Path directory does not appear to exist. Check your <a href='configuration.php'>configuration</a></div>";
}
if($config_newzenabled == "enable"){
	if($config_newzuname == "" || $config_newzpw == ""){ 
		die("<div class='warningmessage'>Username and/or password are not set. Set them in the <a href='configuration.php'>configuration</a> page.</div>"); 
	}
}
if($config_enablenzbget == "enable"){
    if(isset($config_NZBgetAppPath) && isset($config_NZBgetConfigPath)){
      if(!is_dir($config_NZBgetAppPath)) {
          echo "<div class='warningmessage'>The NZBGet Application directory does not appear to exist. Check your <a href='configuration.php'>configuration</a></div>";
          }
      if(!is_dir($config_NZBgetConfigPath)){
          echo "<div class='warningmessage'>The NZBGet Configuration directory does not appear to exist. Check your <a href='configuration.php'>configuration</a></div>";
          }
    } 
}

/*
//mobile or not
if($mobile){
    echo "This appears to be a mobile device.";
    }
elseif($_SERVER['REMOTE_ADDR'] == "127.0.0.1"){
    echo "<h1>Looks like you are on the popcornhour.</h1>";
}
else {
    echo "This appears to be a standard browser.";
}
*/
?>
<div class="block">
  <?php 
  if($config_newzenabled == "enable"){
  ?>
  <h2>Bookmark Utilities</h2>
    <div class="subblock">
      <h3>Bookmark Actions</h3>
      <form action="index.php" method="get">
      <input type="radio" name="action" value="viewbookmarklog"/>View Log for Automatic Job<br />
      <input type="radio" name="action" value="downloadbookmarks"/>Download Bookmarks Now<br />
      <input type="radio" name="action" value="testbookmarkdownload"/>View Bookmarks<br />
      <input type="submit" value="Run Selected Action" onclick="return loadSubmit()"/>
      </form>
    </div>
    <?php
    if($action == "viewbookmarklog") { 
      echo "<div class='subblock'>";
      $fh = fopen($bookmarklogs, 'r');
      $theData = fread($fh, filesize($bookmarklogs));
      fclose($fh);
      echo "Download logs as zip file: <a href='index.php?action=downloadlogzip'>click here</a>";
      echo "<textarea readonly name='logoutput' cols=100 rows=6 wrap='off'>";
      echo $theData;
      echo "</textarea><br />The current 'log' date/time is (".date("Y-m-d").") (".date("g:i a")."). Note: this time may differ from your local time. ";
      //lets get the last line (technically 2) from the log file and make sure the time was within the last 30 minutes.
      define('YOUR_EOL', "\n");
      $fp = fopen($bookmarklogs, 'r');
      $pos = -2; $line = ''; $c = '';
      do {
          $line = $c . $line;
          fseek($fp, $pos--, SEEK_END);
          $c = fgetc($fp);
      } while ($c != YOUR_EOL);
      //echo "The last line of the file was: <pre>$line</pre>";
      fclose($fp);
      //break out the date time from the line
      preg_match("/\(([^\:]+)\) \(([^\-]+)\)/",$line,$matches);
      //if the time from the log is greater than 30 minutes ago, things are running fine. If not, there is probably an issue.
      if(strtotime($matches[1]." ".$matches[2]) >= strtotime("-30 minutes")){ echo "<font color='green'>Job successfully ran within 30 minute window.</font><br />"; } else { echo "<div class='warningmessage'>There appears to be an issue with the cron job running on time</div>"; }
      echo "</div>";
    }
            
    if($action == "downloadlogzip") { 
        echo "Generating download zip file..."; //this shouldn't even show up.

        $zipfile = new zipfile();

        //$zipfile->add_dir("style/");
        //get the list of files in the logs directory
        if ($handle = opendir('../logs/')) {
            while (false !== ($file = readdir($handle))) {
                if ($file != "." && $file != ".." & $file != "cron") {
                    $zipfile->add_file(file_get_contents("../logs/".$file),$file);
                }
            }
            closedir($handle);
        }
        $zipfile->add_file(file_get_contents("../logs/cron/cron.txt"), "cron_log.txt");
        
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header("Content-disposition: attachment; filename=NewzBooklogfiles.zip");
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        //header('Content-Length: ' . filesize($zipfile));
        ob_clean();
        flush();
        
        echo $zipfile->file();
        exit;
    }
    
    if($action == "testbookmarkdownload") { 
        echo "<div class='infomessage'>";
        //use the new post-request code to pull back the reports
        // submit these variables to the server:
        $data = array(
            'username' => $config_newzuname,
            'password' => $config_newzpw,
            'action' => 'fetch'
        );
        // send a request
        list($header, $content) = PostRequest(
            "http://www.newzbin.com/api/bookmarks/",
            "http://popcornhour/NewzBook_web/index.php?action=testbookmarkdownload",
            $data
        );
        // parse out the header and get each line
        $HeaderLines = explode("\n", $header);
        $httpstatus = explode(" ", $HeaderLines[0]);
        if($httpstatus[1] != 200 && $httpstatus[1] != 204) { 
            echo "<div class='warningmessage'>";
            switch ($httpstatus[1]) {
                case 400: 
                    echo "Bad Request. Newzbin didn't understand your request. Check the parameters.";
                    break;
                case 401:
                    echo "Unauthorized. Check your username and password.";
                    break;
                case 402: 
                    echo "Payment Required (the account is not a premium account)";
                    break;
                case 403:
                    echo "Forbidden. Check your username and password.";
                    break;
                case 500: 
                    echo "Internal Server Error (Newzbin broke)";
                    break;
                case 503: 
                    echo "Service Unavailable, site is currently down";
                    break;
                default:
                    if($httpstatus[1] != 200) { echo "Unknown error with HTTP response code $httpstatus[1]"; };
            } 
            echo "</div>";
        } elseif($httpstatus[1] == 204){ echo "There are no bookmarks in your account."; }
        elseif($httpstatus[1] == 200){echo "You currently have the following bookmarks in your NewzBin account.<br /><br />";}
        
        //loop through the array of bookmarks associating each bookmark to a variable
        // split the content into each line
        $ContentLines = explode("\n", $content);
        // for each line, lets format the data we get from Newzbin
        foreach($ContentLines as $CurrLine) {
            //echo $CurrLine;
            if(preg_match('/[0-9]+\t[0-9]+\t.+/', $CurrLine)) {
                // split each line into the different variables
                $SplitContent = explode("\t", $CurrLine);
                $kbytes = (float)$SplitContent[1] / 1024;
                $mbytes = (float)$kbytes / 1024;
                $gbytes = (float)$mbytes / 1024;
                echo "Report ID: $SplitContent[0] <br />";
                echo "Filesize: ";
                    if($mbytes > 1 && $gbytes < 1) { 
                        echo round($mbytes,2)." MB"; 
                    }
                    elseif($gbytes > 1) { 
                        echo round($gbytes,2)." GB";
                    }
                    else {
                        echo round($kbytes,2)." KB"; 
                    }
                echo "<br />";
                echo "Report Name: $SplitContent[2] <br />";
                //echo "<a href='index.php?action=reporttest&reportid=$SplitContent[0]'>Download NZB (via browser)</a> | ";
                echo "<a href='index.php?action=reportactual&reportid=$SplitContent[0]' onclick='return loadSubmit()'>Download now</a>";
                echo "<br /><br />";
            }
        }
        if($httpstatus[1] == 200){echo "<a href='index.php?action=downloadbookmarks' onclick='return loadSubmit()'>Download all bookmarks now!</a>";}
        echo "</div>";
    }
    if($action == "downloadbookmarks") { 
        //do the same thing as the above, but automatically grab all the bookmarks.
        echo "<div class='infomessage'>";
        //use the new post-request code to pull back the reports
        // submit these variables to the server:
        $data = array(
            'username' => $config_newzuname,
            'password' => $config_newzpw,
            'action' => 'fetch'
        );
        // send a request
        list($header, $content) = PostRequest(
            "http://www.newzbin.com/api/bookmarks/",
            "http://popcornhour/NewzBook_web/index.php?action=testbookmarkdownload",
            $data
        );
        // parse out the header and get each line
        $HeaderLines = explode("\n", $header);
        $httpstatus = explode(" ", $HeaderLines[0]);
        if($httpstatus[1] != 200 && $httpstatus[1] != 204) { 
            echo "<div class='warningmessage'>";
            switch ($httpstatus[1]) {
                case 400: 
                    echo "Bad Request. Newzbin didn't understand your request. Check the parameters.";
                    break;
                case 401:
                    echo "Unauthorized. Check your username and password.";
                    break;
                case 402: 
                    echo "Payment Required (the account is not a premium account)";
                    break;
                case 403:
                    echo "Forbidden. Check your username and password.";
                    break;
                case 500: 
                    echo "Internal Server Error (Newzbin broke)";
                    break;
                case 503: 
                    echo "Service Unavailable, site is currently down";
                    break;
                default:
                    if($httpstatus[1] != 200) { echo "Unknown error with HTTP response code $httpstatus[1]"; };
            } 
            echo "</div>";
        } elseif($httpstatus[1] == 204){ echo "There are no bookmarks in your account."; }
        elseif($httpstatus[1] == 200){echo "The following bookmarks have been downloaded to the $config_NZBDropPath directory.<br /></br>";}
        
        //loop through the array of bookmarks associating each bookmark to a variable
        // split the content into each line
        $ContentLines = explode("\n", $content);
        // for each line, lets format the data we get from Newzbin
        foreach($ContentLines as $CurrLine) {
            //echo $CurrLine;
            if(preg_match('/[0-9]+\t[0-9]+\t.+/', $CurrLine)) {
                // split each line into the different variables
                $SplitContent = explode("\t", $CurrLine);
                //tell the user what file we are downloading
                echo "Attempting to download $SplitContent[2] via report $SplitContent[0] <br />";
                //download the NZB
                //use the new post-request code to pull back the reports
                // submit these variables to the server:
                $data = array(
                    'username' => $config_newzuname,
                    'password' => $config_newzpw,
                    'reportid' => $SplitContent[0]
                );
                 
                // send a request
                list($header, $content) = PostRequest(
                    "http://www.newzbin.com/api/dnzb/",
                    "http://popcornhour/NewzBook_web/index.php",
                    $data
                );
                
                // parse out the header and get each line
                $HeaderLines = explode("\n", $header);
                // for each line, lets format the data we get from Newzbin
                foreach($HeaderLines as $CurrLine) {
                    //make sure it's a line with a variable
                    preg_match('/([^:]+): (.+)/',$CurrLine,$HdrLineContent);         
                    //if the variables are set clean and assign them
                    if(isset($HdrLineContent[1]) && isset($HdrLineContent[2])) {
                        //remove dash from header
                        $HdrLineContent[1] = str_replace("-","_",$HdrLineContent[1]);
                        //assign content to variable name
                        ${$HdrLineContent[1]} = $HdrLineContent[2];
                    }
                }

                if($X_DNZB_RCode == 200) {
                    //create arrays
                    $dirty2dash = array("/");
                    $nzbfilename = str_replace($dirty2dash,"-",trim($X_DNZB_Name));
                    $dirty2remove = array(":");
                    $nzbfilename = str_replace($dirty2remove,"",$nzbfilename);
                    //create the NZB in the NZB library
                    $nzbfilename = $config_NZBDropPath . "/" . $nzbfilename . ".nzb";
                    //echo "I'm going to write to the file: $nzbfilename <br />";
                    $fh = fopen($nzbfilename, 'w'); // or die("can't open file $nzbfilename <br />");
                    if($fh != FALSE) {
                        echo "Writing to file $nzbfilename <br />";
                        if(fwrite($fh, $content) != FALSE){ //or die("can't write to file $nzbfilename <br />");
                            //We successfully wrote the NZB, lets remove it from the bookmarks if the user wants
                            if($config_deleteupondl == "delon"){
                                $data = array(
                                    'username' => $config_newzuname,
                                    'password' => $config_newzpw,
                                    'action' => 'delete',
                                    'reportids' => $SplitContent[0]
                                );
                                 
                                // send a request
                                list($deleteheader, $deletecontent) = PostRequest(
                                    "http://www.newzbin.com/api/bookmarks/",
                                    "http://popcornhour/NewzBook_web/index.php",
                                    $data
                                );
                                echo "Removing reportID $SplitContent[0] from newzbin bookmarks<br />";
                            } else { echo "Delete option is turned off. Report $SplitContent[0] will stay in your bookmarks<br />"; }
                        } else { echo "<div class='warningmessage'>Can't write to file $nzbfilename </div>"; }
                        fclose($fh);
                    } else { echo "<div class='warningmessage'>Couldn't open file $nzbfilename </div>"; }
                    echo "<br />";
                    //exit;
                } 
                else { 
                    echo "<div class='warningmessage'>Error with response code: $X_DNZB_RCode <br />"; 
                    ECHO "Error Message: $X_DNZB_RText</div>";
                }
            }
        }
        echo "</div>";
    }
    ?>
    </div>
  <?php } // end block for hiding bookmark management if newzbin isn't enabled 
  else {
	// echo "<h2>Welcome!</h2>";
  }
  ?>
    <div class="subblock">
      <h3>Download NZB via ReportID</h3
      <form action="index.php" method="get">
      <!-- <input type="radio" name="action" value="reporttest">Download NZB (via browser)<br /> -->
      <!-- <input type="radio" name="action" value="reportactual">Download NZB (directly to Usenet client)<br /> -->
      <div class="fielddesc">Report ID/URL:</div><input type="text" name="reportid" value="<?php if(isset($_GET['reportid'])) { echo $_GET['reportid']; } ?>"/><br />
      <input type="submit" value="Download Now" onclick="return loadSubmit()"/>
      </form>
      <?php 
      //If there is something in that variable, let's do something with it
      if(isset($newzbinreportID)) { 
        if($newzbinreportID == NULL && ($action == "reporttest" || $action == "reportactual")) {
          die("You didn't enter a Report ID...try a sample one: <a href='index.php?reportid=5068710'>5068710</a>");
        }
      }
      
	  //if we got here, then the report isn't NULL, so let's perform the action
      if(($action == "reporttest" || $action="reportactual") && $newzbinreportID != NULL) {
        //temporary solution to get NZBMatrix downloads working -- the overall download code will need to be refactored
		if(isset($_GET['indexer'])){if(strtolower($_GET['indexer']) == "nzbmatrix"){
			/* There are too many limits with the matrix API right now -- this prevents me from adding category support using their report details api
			//match Matrix Category to default SAB categories
			$url = 'http://nzbmatrix.com/api-nzb-details.php?id='.$newzbinreportID.'&username='.$config_nzbmatrixuname.'&apikey='.$config_nzbmatrixapikey;
			//filter out the category from the nzb details
			echo "<pre>".file_get_contents($url)."</pre>";
			preg_match('/CATEGORY\:(.*)( > .*)/i', file_get_contents($url), $category);
			echo "<br />";
			print_r($category);
			echo "<br />";
			*/
			
			//Alternative method for categories (coming directly from search)
			preg_match('/(CATEGORY\:)?([^ >]+)( > .*)?/i', $category, $category);
			$category = $category[2];
			
			//build the url to get the NZB
			$url = 'http://nzbmatrix.com/api-nzb-download.php?id='.$newzbinreportID.'&username='.$config_nzbmatrixuname.'&apikey='.$config_nzbmatrixapikey;
			//get the contents of the NZB
			$content = file_get_contents($url);
			
			//do some basic error checking
			if(substr($content, 0, 6) == 'error:'){
				echo "<div class='warningmessage'>";
					switch ($content) {
						case "error:invalid_login":
							echo "There is a problem with the username you have provided.";
							break;
						case "error:invalid_api": 
							echo "There is a problem with the API Key you have provided.";
							break;
						case "error:invalid_nzbid": 
							echo "There is a problem with the NZBid supplied.";
							break;
						case "error:please_wait_x":
							echo "Please wait x seconds before retry.";
							break;
						case "error:vip_only":
							echo "You need to be VIP or higher to access.";
							break;
						case "error:disabled_account":
							echo "User Account Disabled.";
							break;
						case "error:x_daily_limit":
							echo "You have reached the daily download limit of x.";
							break;
						case "error:no_nzb_found":
							echo "No NZB found.";
							break;
						default:
							echo $content;
					}
				echo "</div>";
			}
			else{
				if(isset($reportName)){ $nzbfilename = $reportName; } //***probably need to come back and look at this (strip bad characters)
				else{ $nzbfilename = "nzbmatrix_".$newzbinreportID; }
				//save to the drop path
				if($config_sabnzbdnaming_enable == 'enable'){
					/* --- Category Style Naming --- */
					//Check to see if the category folder exists
					if(file_exists($config_NZBDropPath . "/" . $category . "/")){
						//if the category folder exists, let's save the file there
						$nzbfilename = $config_NZBDropPath . "/" . $category . "/" . $nzbfilename . ".nzb"; 
					}else{
						//otherwise let's try to create the folder
						if(mkdir($config_NZBDropPath . "/" . $category)){
							echo "Created the directory ".$config_NZBDropPath . "/" . $category." <br />";
							//make sure the permissions are set so other users on the system can use the folder we created
							chmod($config_NZBDropPath . "/" . $category, 0777);
							//----->I would like to put some chown chgrp stuff in here, but I would need to know everyone's user
							//if we can create the folder, let's save it there
							$nzbfilename = $config_NZBDropPath . "/" . $category . "/" . $nzbfilename . ".nzb"; 						
						}else{
							//if that fails, let's save it in the normal location using the sabnzbd style category in the name
							$nzbfilename = $config_NZBDropPath . "/{{" . $category . "}}" . $nzbfilename . ".nzb"; 
						}
					}
				}else{
					/* --- Regular Style Naming --- */
					//If the user doesn't want SAB category support, let's use basic naming without category support
					$nzbfilename = $config_NZBDropPath . "/" . $nzbfilename . ".nzb"; 
				}
					//echo "I'm going to write to the file: $nzbfilename <br />";
					$fh = fopen($nzbfilename, 'w'); // or die("can't open file $nzbfilename <br />");
					if($fh != FALSE) {
						echo "Writing to file $nzbfilename <br />";
						if(fwrite($fh, $content) != FALSE){ //or die("can't write to file $nzbfilename <br />");
							//successfully wrote NZB
							echo "<div class='infomessage'>Successfully downloaded and wrote NZB as $nzbfilename</div>";
						} else { echo "<div class='warningmessage'>Can't write to file $nzbfilename </div>"; }
						fclose($fh);
					} else { echo "<div class='warningmessage'>Couldn't open file $nzbfilename </div>"; }
			}
		}}
		else{
		/*----------------------------*\
	     |  Get Newzbin NZB by Report |
	    \*----------------------------*/
		//use the new post-request code to pull back the reports
        // submit these variables to the server:
        $data = array(
            'username' => $config_newzuname,
            'password' => $config_newzpw,
            'reportid' => $newzbinreportID
        );
         
        // send a request
        list($header, $content) = PostRequest(
            "http://www.newzbin.com/api/dnzb/",
            "http://popcornhour/NewzBook_web/index.php",
            $data
        );
        
        // parse out the header and get each line
        $HeaderLines = explode("\n", $header);
        // for each line, lets format the data we get from Newzbin
        foreach($HeaderLines as $CurrLine) {
            //make sure it's a line with a variable
            preg_match('/([^:]+): (.+)/',$CurrLine,$HdrLineContent);         
            //if the variables are set clean and assign them
            if(isset($HdrLineContent[1]) && isset($HdrLineContent[2])) {
                //remove dash from header
                $HdrLineContent[1] = str_replace("-","_",$HdrLineContent[1]);
                //assign content to variable name
                ${$HdrLineContent[1]} = $HdrLineContent[2];
            }
        }

        if($X_DNZB_RCode == 200) {
            //generate the file
            if($action == "reporttest" && $newzbinreportID != NULL) {
                if(isset($content)){
                    //create arrays
                    $dirty2dash = array("/");
                    $nzbfilename = str_replace($dirty2dash,"-",trim($X_DNZB_Name));
                    $dirty2remove = array(":");
                    $nzbfilename = str_replace($dirty2remove,"",$nzbfilename);
                    header('Content-Description: File Transfer');
                    header('Content-Type: application/octet-stream');
                    header('Content-Disposition: attachment; filename="'.$nzbfilename.'.nzb"'); 
                    header('Content-Transfer-Encoding: binary');
                    header('Expires: 0');
                    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                    header('Pragma: public');
                    header('Content-Length: ' . filesize($newzbinreportID));
                    ob_clean();
                    flush();
                    echo $content;
                    exit;
                }
            }
            if($action == "reportactual" && $newzbinreportID != NULL) {
                echo "<div class='infomessage'>";
                //create arrays
                $dirty2dash = array("/");
                $nzbfilename = str_replace($dirty2dash,"-",trim($X_DNZB_Name));
                $dirty2remove = array(":");
                $nzbfilename = str_replace($dirty2remove,"",$nzbfilename);
                //create the NZB in the NZB library
                //$nzbfilename = $config_NZBDropPath . "/" . $nzbfilename . ".nzb"; //OLD METHOD
				
				//save to the drop path
				if($config_sabnzbdnaming_enable == 'enable'){
					/* --- Category Style Naming --- */
					//Check to see if the category folder exists
					if(file_exists($config_NZBDropPath . "/" . $category . "/")){
						//if the category folder exists, let's save the file there
						$nzbfilename = $config_NZBDropPath . "/" . $category . "/" . $nzbfilename . ".nzb"; 
					}else{
						//otherwise let's try to create the folder
						if(mkdir($config_NZBDropPath . "/" . $category)){
							echo "Created the directory ".$config_NZBDropPath . "/" . $category." <br />";
							//make sure the permissions are set so other users on the system can use the folder we created
							chmod($config_NZBDropPath . "/" . $category, 0777);
							//----->I would like to put some chown chgrp stuff in here, but I would need to know everyone's user
							//if we can create the folder, let's save it there
							$nzbfilename = $config_NZBDropPath . "/" . $category . "/" . $nzbfilename . ".nzb"; 						
						}else{
							//if that fails, let's save it in the normal location using the sabnzbd style category in the name
							$nzbfilename = $config_NZBDropPath . "/{{" . $category . "}}" . $nzbfilename . ".nzb"; 
						}
					}
				}else{
					/* --- Regular Style Naming --- */
					//If the user doesn't want SAB category support, let's use basic naming without category support
					$nzbfilename = $config_NZBDropPath . "/" . $nzbfilename . ".nzb"; 
				}
                //echo "I'm going to write to the file: $nzbfilename <br />";
                $fh = fopen($nzbfilename, 'w'); // or die("can't open file $nzbfilename <br />");
                if($fh != FALSE) {
                    echo "Writing to file $nzbfilename <br />";
                    if(fwrite($fh, $content) != FALSE){ //or die("can't write to file $nzbfilename <br />");
                        //We successfully wrote the NZB, lets remove it from the bookmarks if the user wants
                        if($config_deleteupondl == "delon"){
                            $data = array(
                                'username' => $config_newzuname,
                                'password' => $config_newzpw,
                                'action' => 'delete',
                                'reportids' => $newzbinreportID
                            );
                             
                            // send a request
                            list($deleteheader, $deletecontent) = PostRequest(
                                "http://www.newzbin.com/api/bookmarks/",
                                "http://popcornhour/NewzBook_web/index.php",
                                $data
                            );
                            echo "Removing reportID $SplitContent[0] from newzbin bookmarks<br />";
                        } else { echo "Delete option is turned off. Report $SplitContent[0] will stay in your bookmarks<br />"; }
                    } else { echo "<div class='warningmessage'>Can't write to file $nzbfilename </div>"; }
                    fclose($fh);
                } else { echo "<div class='warningmessage'>Couldn't open file $nzbfilename </div>"; }
                echo "Current Memory: ".memory_get_usage()." | Peak Memory: ".memory_get_peak_usage()."\n";
                echo "</div><br />";
                //exit;
            }
        }
        else { 
            echo "<div class='warningmessage'>Error with response code: $X_DNZB_RCode <br />"; 
            ECHO "Error Message: $X_DNZB_RText</div>";
        }
	   }
	  } 
    ?>
   </div>
</div>

</div>
</BODY>